# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.utils import timezone

from django.shortcuts import render
from django.views import generic

from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, Http404
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail, EmailMultiAlternatives
# from redis_cache import get_redis_connection
from django.core.cache import cache

from django import forms
from django.forms.models import model_to_dict

# import io
# from backend import check_code as CheckCode



from .models import IndexBannerPic
from .models import IndexNoticeMessage
from .models import Account
# from .models import Brand
# from .models import Product
from .models import Material
from .models import SmerpErpinfo
from .models import SmerpBrand as Brand
from .models import SmerpBrandLicense as BrandLicense
from .models import SmerpProduct as Product
from .models import SmerpProductImg
from .models import SmerpProductLicense as ProductLicense
from .models import SmerpMaterial
from .models import SmerpProductMaterial as ProductMaterial
from .models import SmerpSmcodeOrder
from .models import SmerpSmcode
from .models import SmerpPublishSmcodeLog
from .models import WxmpScanLog
from .models import WxmpAbnormalLog
from .models import WxmpFeedback
from .models import SmplatConfig


import os, sys
import time, datetime
import json
import copy
import hashlib
import xlwt
import base64

from decimal import Decimal
from tools import rc4
from tools import tools as tl

import logging
#logger = logging.getLogger(__name__) # 为loggers中定义的名称
#logger.info(__name__)
logger = logging.getLogger("smErp")  # 为loggers中定义的名称
# print __name__

import config
# import tools

# 生成验证码

from PIL import Image, ImageDraw, ImageFont, ImageFile, ImageFilter
# from django.http.response import HttpResponse
# from django.settings import BASE_DIR
from django.conf import settings

import cStringIO, string, random


class SMJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, Decimal):
            # return str(obj)
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)

# full_name=&organization_code=&registration_no=&representative=&scope_normal=&scope_sepcial=&staff_num=&manager=&manager_phone=&manager_id_card_no=
# full_name=&organization_code=&registration_no=&representative=&scope_normal=&scope_sepcial=&staff_num=&manager=&manager_phone=&manager_id_card_no=
class companyForm(forms.Form):
    """
    企业信息表单
    """
    full_name = forms.CharField(max_length=64)
    organization_code = forms.CharField(max_length=32)
    registration_no = forms.CharField(max_length=32)
    representative = forms.CharField(max_length=32)
    scope_normal = forms.CharField(max_length=1000, min_length=0, empty_value='')
    # scope_sepcial = forms.CharField(min_length=0, empty_value='')
    # staff_num = forms.IntegerField()
    # licence_img = forms.CharField(max_length=128)
    manager = forms.CharField(max_length=32)
    manager_phone = forms.CharField(max_length=16)
    manager_id_card_no = forms.CharField(max_length=32)
    # manager_id_card_img = forms.CharField(max_length=128)

def randomColor():
    r = random.randint(0, 256)
    g = random.randint(0, 256)
    b = random.randint(0, 256)
    return (r, g, b)

# image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #创建扭曲
#     image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜，边界加强
def smErpCaptcha(request):
    '''Captcha'''
    try:
        width = 147
        height = 49
        image = Image.new('RGB', (147, 49), color = (255, 255, 255)) # model, size, background color
        font_file = os.path.join(settings.BASE_DIR, 'smErp/static/smErp/media/fonts/arial.ttf') # choose a font file
        # print font_file
        font = ImageFont.truetype(font_file, 40) # the font object
        draw = ImageDraw.Draw(image)
        rand_str = ''.join(random.sample(string.letters + string.digits, 4)) # The random string
        j = 0
        for i in rand_str:
            draw.text((7 + j * 30, 0), i, fill=randomColor(), font=font) # position, content, color, font
            j += 1
        del draw
        request.session['captcha'] = rand_str.lower() # store the content in Django's session store
        buf = cStringIO.StringIO() # a memory buffer used to store the generated image
        # image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #创建扭曲
        # image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜，边界加强
        image.save(buf, 'jpeg')
    except Exception, e:
        logger.error(e.message, exc_info=True)

    return HttpResponse(buf.getvalue(), 'image/jpeg') # return the image data stream as image/jpeg format, browser will treat it as an image


# Create your views here.
def smErpActive(request):
    """
    邮箱账号激活
    :param request:
    :return:
    """
    if request.method == "GET":
        # 邮箱激活
        md5_token = request.GET.get("token", "")
        # 缓存中取出账号
        email = cache.get(md5_token)
        if not email:
            # todo 跳转到错误提示页面
            # print u"对应的token[%s]缓存中不存在账号"%(email)
            raise Http404(u"页面不存在")

        # 删除缓存
        cache.delete(md5_token)
        cache.delete(email)
        # 找到对应的账号，并激活
        try:
            user = Account.account_manager.get(email=email, email_vaild=0)
        except (KeyError, Account.DoesNotExist):
            # print u"email[%s]数据库中不存在未激活记录"%(email)
            # 删除缓存
            raise Http404(u"页面不存在")

        # 更新用户的状态为邮箱验证， 有户的可用状态等填完企业资料后更新
        user.email_vaild = 1
        user.save()
        # 重定向到完善企业资料的视图
        request.session["email"] = email
        request.session["passwd"] = user.passwd
        return HttpResponseRedirect(reverse("smErp:complete_company"))


def smErpCompleteCompany(request):
    """
    完善企业资料视图
    :param request:
    :return:
    """
    # pass
    # 取出session中的用户信息
    email = request.session.get("email","")
    passwd = request.session.get("passwd","")
    if not (email and passwd):
        logger.error(u"不存在用户的登录信息[%s][%s]"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))

    # 查出对应的用户
    try:
        user = Account.account_manager.get(email = email, passwd = passwd, email_vaild = 1)
    except (KeyError, Account.DoesNotExist):
        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == "POST":
        logger.info(u"完善企业资料")
        action = request.POST.get("action","")

        if action not in ("create", "change"):
            logger.error(u"参数错误，action[%s]"%(action))
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")

        full_name = request.POST.get("full_name","")        # 企业全称
        organization_code = request.POST.get("organization_code","") # 组织机构代码
        registration_no = request.POST.get("registration_no","")        # 工商执照号
        representative = request.POST.get("representative","")          # 法人
        scope_normal = request.POST.get("scope_normal","")              # 一般经营范围
        scope_sepcial = request.POST.get("scope_sepcial","")            # 特殊经营范围
        staff_num = request.POST.get("staff_num", 0)                    # 企业员工人数
        manager = request.POST.get("manager","")                        # 管理员
        manager_phone = request.POST.get("manager_phone", "")           # 管理员手机号
        manager_id_card_no = request.POST.get("manager_id_card_no", "") # 管理员身份证号码
        licence_img = request.POST.get('licence_img',"")                # 营业执照
        manager_id_card_img = request.POST.get("manager_id_card_img", "")   # 管理员身份证照

        try:
            if not staff_num:
                staff_num = 0
            else:
                staff_num = int(staff_num)
            # 创建企业信息
            if action == "create":
                # 企业信息不能存在
                company_info = SmerpErpinfo.erpinfo_manage.filter(account_id = user.id)
                if company_info:
                    logger.error(u"用户[%s]企业信息已经存在，不能新建"%(email))
                    return HttpResponse(json.dumps(config.getErrInfo("CompanyExistError")), content_type="application/json")
                # pass
                if not full_name:
                    logger.error(u"企业名称未填写")
                    return HttpResponse(json.dumps(config.getErrInfo("CompanyNeedError")), content_type="application/json")
                 # 企业全称不能重复
                company_info = SmerpErpinfo.erpinfo_manage.filter(full_name = full_name)
                if company_info:
                    logger.error(u"创建企业信息错误, 企业名称重复", exc_info=True)
                    ret = config.getErrInfo("CompanyNameRepeat")
                    return HttpResponse(json.dumps(ret), content_type="application/json")

                # 创建
                smErpInfo = SmerpErpinfo(account=user, full_name=full_name, staff_num=staff_num)
                if organization_code:
                    smErpInfo.organization_code = organization_code
                if registration_no:
                    smErpInfo.registration_no = registration_no
                if representative:
                    smErpInfo.representative = representative
                if scope_normal:
                    smErpInfo.scope_normal = scope_normal
                if scope_sepcial:
                    smErpInfo.scope_sepcial = scope_sepcial
                if manager:
                    smErpInfo.manager = manager
                if manager_phone:
                    smErpInfo.manager_phone = manager_phone
                if manager_id_card_no:
                    smErpInfo.manager_id_card_no = manager_id_card_no
                if licence_img:
                    smErpInfo.licence_img = licence_img
                if manager_id_card_img:
                    smErpInfo.manager_id_card_img = manager_id_card_img
                smErpInfo.check_status = 1
                smErpInfo.save()
                logger.info(u"用户[%s]的企业[%s]信息创建成功"%(email, full_name))
                return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")
            else:
                # 修改企业信息
                # 判断用户企业信息是否已经存在
                try:
                    smErpInfo = SmerpErpinfo.erpinfo_manage.get(account_id = user.id )
                except(KeyError, SmerpErpinfo.DoesNotExist):
                    logger.error(u"还没有用户[%s]对应的企业信息"%(email), exc_info=True)
                    return HttpResponse(json.dumps(config.getErrInfo("CompanyNotExistError")), content_type="application/json")
                # 更新企业信息
                if staff_num: smErpInfo.staff_num = staff_num
                if organization_code:
                    smErpInfo.organization_code = organization_code
                if registration_no:
                    smErpInfo.registration_no = registration_no
                if representative:
                    smErpInfo.representative = representative
                if scope_normal:
                    smErpInfo.scope_normal = scope_normal
                if scope_sepcial:
                    smErpInfo.scope_sepcial = scope_sepcial
                if manager:
                    smErpInfo.manager = manager
                if manager_phone:
                    smErpInfo.manager_phone = manager_phone
                if manager_id_card_no:
                    smErpInfo.manager_id_card_no = manager_id_card_no
                if licence_img:
                    smErpInfo.licence_img = licence_img
                if manager_id_card_img:
                    smErpInfo.manager_id_card_img = manager_id_card_img
                smErpInfo.check_status = 1
                smErpInfo.save()
                logger.info(u"用户[%s]企业信息修改成功"%(email))
                return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")


        except Exception, e:
            logger.error(u"用户[%s]企业信息发生异常：%s"%(email,e.message), exc_info=True)
            return HttpResponse(json.dumps(config.getErrInfo("SystemError")), content_type="application/json")

    if request.method == "GET":
        # try:
        #     company_info = SmerpErpinfo.erpinfo_manage.get(account_id = user.id)
        # except(KeyError, SmerpErpinfo.DoesNotExist):
        #     logger.error(u"用户[%s]还未录入企业信息"%(email), exc_info=True)
        #     company_info = {}
        company_info = SmerpErpinfo.erpinfo_manage.filter(account_id = user.id).first()
        if not company_info:
            logger.error(u"用户[%s]还未录入企业信息"%(email))
            company_info = {}

        return render(request, 'smErp/complete_company.html', {"user_info": user, "company_info": company_info})


# Create your views here.
class IndexView(generic.ListView):
    model = IndexBannerPic
    template_name = "smErp/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['notice_message_list'] = IndexNoticeMessage.objects.order_by("-pk")[:10]
        return context

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()
        email = request.session.get('email', None)
        passwd = request.session.get('passwd', None)
        if not allow_empty:
            if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
                is_empty = not self.object_list.exists()
            else:
                is_empty = len(self.object_list) == 0
            if is_empty:
                raise Http404("页面不存在")

        context = self.get_context_data()
        if email and passwd:
            try:
                user = Account.account_manager.get(email__exact = email,passwd__exact = passwd)
            except(KeyError, Account.DoesNotExist):
                logger.error(u"用户[%s][%s]未登录"%(email, passwd))
                # 清除session
                del request.session["email"]
                del request.session["passwd"]
                user = None
            context["user_info"] = user
        return self.render_to_response(context)


class UserForm(forms.Form):
    email = forms.EmailField(label='邮箱',max_length=100)
    passwd = forms.CharField(label='密码',widget=forms.PasswordInput())
    # verify = forms.CharField(label='验证码', max_length=4, min_length=4,)


@csrf_exempt
def smErpLogin(request):
    """
    登录
    :param request:
    :return:
    """
    if request.META.has_key('HTTP_X_FORWARDED_FOR'):
        ip =  request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']

    if request.method == "POST":
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            # print "i mah ere"
            email = user_form.cleaned_data["email"]
            _passwd = user_form.cleaned_data["passwd"]
            #是否需要对passwd加密
            passwd = hashlib.md5("%s%s"%(_passwd, config.PASSWORD_KEY)).hexdigest()
            user = Account.account_manager.filter(email__exact = email,passwd__exact = passwd).first()
            if user:
                # user = user[0]
                # 更新登录时间， 登录ip
                request.session['email'] = email
                request.session['passwd'] = passwd
                user.login_time = timezone.now()
                user.login_ip = ip
                user.save()
                # 判断用户是否已经通过邮箱验证
                if user.email_vaild == 1 and user.is_active == 1:
                    # return HttpResponseRedirect('/smErp/index/')
                    ret = config.getErrInfo("Success")
                    return HttpResponse(json.dumps(ret), content_type="application/json")
                else:
                    if user.email_vaild != 1:
                        logger.error(u"账号：%s 还未邮件进行激活"%(email))
                        ret = config.getErrInfo("AccountNoVaild")
                        return HttpResponse(json.dumps(ret), content_type="application/json")
                        # 跳转到注册页面
                        # return HttpResponseRedirect(reverse("smErp:register"))

                    if user.is_active != 1:
                        logger.error(u"账号：%s 还未完成企业信息录入"%(email))
                        ret = config.getErrInfo("AccountNoCompany")
                        return HttpResponse(json.dumps(ret), content_type="application/json")

            else:
                logger.error(u"用户的账号[%s]密码[%s]错误"%(email, _passwd))
                ret = config.getErrInfo("AccountPwdError")
                return HttpResponse(json.dumps(ret), content_type="application/json")

        else:
            ret = config.getErrInfo("AccountPwdError")
            return HttpResponse(json.dumps(ret), content_type="application/json")


def smErpLogout(request):
    """
    退出登录
    :param request:
    :return:
    """
    # 清除session里的用户信息
    # 跳转到首页
    if request.session.get("email", None):
        del request.session["email"]
    if request.session.get("passwd", None):
        del request.session["passwd"]
    return HttpResponseRedirect(reverse("smErp:index"))



def send_register_mail(email):
    """
    发送注册激活邮件，返回token
    :param email:
    :return:
    """
    date_day = timezone.now().strftime("%Y%m%d%H%M%S")
    try:
        from_email = settings.EMAIL_FROM
        # print from_email
        to = email
        # 生成token
        cache_token = "%s:%s"%(email, date_day,)
        token = hashlib.md5(cache_token).hexdigest()

        subject = '请激活你的中国保健溯源平台帐号'
        active_url = "http://%s/smErp/active?token=%s" % (config.HOST, token)
        # text_content = 'This is an important message.'
        html_content = '<div><p>你好!</p><p>感谢你注册中国保健溯源平台。<br>你的登录邮箱为：%s。请点击以下链接激活帐号：</p><p style="word-wrap:break-word;word-break:break-all;"><a href="%s" target="_blank">%s</a></p><p>如果以上链接无法点击，请将上面的地址复制到你的浏览器(如IE)的地址栏进入平台。 （该链接在48小时内有效，48小时后需要重新注册）</p></div>' % (
              email, active_url, active_url)
        text_content = ''
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        return token
    except Exception, e:
        # print u"发送注册激活邮件失败:%s"% e.message
        return None



def __send_mail(email, subject, html_message):
    """
    发送邮件，返回token
    :param email:
    :return:
    """
    try:
        from_email = settings.EMAIL_FROM
        recipient_list = [email]
        # subject = '请激活你的中国保健溯源平台帐号'
        # active_url = "http://%s/%s?token=%s&email=%s" % (config.HOST, action, token, email_encrypt)
        message = ""
        return send_mail(subject, message, from_email, recipient_list, html_message = html_message)
    except Exception, e:
        # print u"发送注册激活邮件失败:%s"% e.message
        return False



def smErpRegister(request):
    """
    注册
    :param request:
    :return:
    """
    s_verify = request.session.get("captcha", "")
    logger.info(u"========== 注册 ==========，session 中保存的验证码[%s]" % (s_verify,))

    if request.method == 'POST':
        uf = UserForm(request.POST)
        if uf.is_valid():
            #获得表单数据
            email = uf.cleaned_data['email']
            password = uf.cleaned_data['passwd']
            verify = request.POST["verify"]
            # 校验验证码
            if verify.lower() != s_verify.lower():
                # 验证码错误
                ret = config.getErrInfo("VerifyCodeError")
                return HttpResponse(json.dumps(ret), content_type="application/json")

            # 判断数据库中是否存在邮箱激活账号
            logger.info(u"注册：邮箱[%s]" % (email,))
            # 判断数据库中是否存在邮箱激活账号
            _account = Account.account_manager.filter(email=email).first()
            if _account:  # 存在账号
                logger.warn(u"注册：邮箱[%s]，账号已经存在，邮箱是否验证[%s]；错误：账号已经存在" % (email, _account.email_vaild))
                ret = config.getErrInfo("AccountExistError")
                return HttpResponse(json.dumps(ret), content_type="application/json")
            # 发邮件
            mail_token = send_register_mail(email)
            # 将token存入缓存中
            if not mail_token:
                # print u"token"
                ret = config.getErrInfo("SystemError")
                return HttpResponse(json.dumps(ret), content_type="application/json")

            try:
                cache_token = cache.get(email)
                if cache_token:
                    # old_token = cache.get(email)
                    cache.delete(cache_token)
                    # todo 需要增加防刷机制
                # 更新缓存中信息
                cache.set(mail_token, email, 48 * 60 * 60)
                cache.set(email, mail_token, 48 * 60 * 60)
            except Exception, e:
                # print e.message
                # print u"将token存入cache中失败"
                ret = config.getErrInfo("SystemError")
                return HttpResponse(json.dumps(ret), content_type="application/json")

            # print "mail_token: %s"%(cache.get(mail_token))
            # 添加到数据库
            md5_pwd = hashlib.md5("%s%s" % (password, config.PASSWORD_KEY)).hexdigest()
            account = Account(email=email, passwd=md5_pwd, email_vaild=0, is_active=1, create_time=timezone.now())
            account.save()
            logger.info(u"邮箱[%s]注册成功，密码为[%s]" % (email, password))

            # 写入session
            ret = config.getErrInfo("Success")
            return HttpResponse(json.dumps(ret), content_type="application/json")
        else:
            ret = config.getErrInfo("ParamsError")
            reason = ""
            for field_name, errs in uf.errors.items():
                reason += ",".join(errs)
            ret["reason"] = reason
            logger.error(u"参数不合法：%s" % (ret,))
            return HttpResponse(json.dumps(ret), content_type="application/json")

    if request.method == "GET":
        # uf = UserForm()
        email = request.session.get("email", "")
        password = request.session.get("passwd","")
        try:
            user = Account.account_manager.get(email__exact = email,passwd__exact = password)
        except (KeyError, Account.DoesNotExist):
            logger.error(u"没有对应的用户信息[%s][%s]"%(email, password))
            user = None
        email_server = ""
        if user:
            email_server = "http://mail." + user.email.split("@")[1]
            if user.email_vaild == 1:
                # 用户的邮箱已经激活，跳转到企业信息界面
                return HttpResponseRedirect(reverse("smErp:complete_company"))
        # return render_to_response('smErp/register.html',context=RequestContext(request))
        return render(request, 'smErp/register.html', {"user_info": user, "email_server": email_server})


def smErpResendMail(request):
    """
    重发激活邮件
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd","")
    if not (email and passwd):
        logger.error(u"不存在用户的登录信息[%s][%s]"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))

    # 查出对应的用户
    try:
        user = Account.account_manager.get(email = email, passwd = passwd)
    except (KeyError, Account.DoesNotExist):
        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == 'POST':
        # 发邮件
        mail_token = send_register_mail(email)
        # 将token存入缓存中
        if not mail_token:
            # print u"token"
            ret = config.getErrInfo("SystemError")
            return HttpResponse(json.dumps(ret), content_type="application/json")
        try:
            cache_token = cache.get(email)
            if cache_token:
                # old_token = cache.get(email)
                cache.delete(cache_token)
                # todo 需要增加防刷机制
            # 更新缓存中信息
            cache.set(mail_token, email, 48 * 60 * 60)
            cache.set(email, mail_token, 48 * 60 * 60)
        except Exception, e:
            # print e.message
            # print u"将token存入cache中失败"
            ret = config.getErrInfo("SystemError")
            return HttpResponse(json.dumps(ret), content_type="application/json")
        logger.info(u"[%s]重新发送激活邮件成功"%(email))
        return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")


# @login_required(login_url='/accounts/login/')
class smErpManage(generic.ListView):
    model = Brand
    template_name = "smErp/manage.html"

    def get_context_data(self, **kwargs):
        # print "wo zhixingle "
        # Call the base implementation first to get a context
        context = super(smErpManage, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['product_list'] = Product.product_manage.order_by("-create_time")[:10]
        context['material_list'] = Material.material_manage.order_by("-create_time")[:10]
        # print context["notice_message_list"]
        return context

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()
        email = request.session.get('email', None)
        passwd = request.session.get('passwd', None)
        if not allow_empty:
            # When pagination is enabled and object_list is a queryset,
            # it's better to do a cheap query than to load the unpaginated
            # queryset in memory.
            if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
                is_empty = not self.object_list.exists()
            else:
                is_empty = len(self.object_list) == 0
            if is_empty:
                raise Http404("页面不存在")

        context = self.get_context_data()
        # if user:
        if email and passwd:
            print "i am here", email
            try:
                user = Account.account_manager.get(email__exact = email,passwd__exact = passwd)
            except (KeyError, Account.DoesNotExist):
                logger.error(u"没有对应的用户信息")
                return HttpResponseRedirect(reverse("smErp:index"))
            else:
                is_actived = user.is_active
                if not is_actived:
                    logger.error(u"用户email[%s]未激活"%(email))
                    # 跳转到等待审核状态
                    raise Http404(u"页面不存在")
            # 用户的企业信息
            try:
                smErpInfo = SmerpErpinfo.erpinfo_manage.get(account_id = user.id)
            except (KeyError, SmerpErpinfo.DoesNotExist):
                logger.error(u"用户[%s]还没完善企业资料"%(account))
                raise Http404(u"页面不存在")
            # 企业资料是否审核通过
            # print user
            context["user_info"] = user
            context["company_status"] = smErpInfo.check_status
        else:
            return HttpResponseRedirect(reverse("smErp:index"))
        print context
        return self.render_to_response(context)


def user_authenticate(function_view):
    def wrapped_view(request, *args, **kwargs):
        email = request.session.get('email', "")
        passwd = request.session.get('passwd', "")
        if not (email and passwd):
            logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
            return HttpResponseRedirect(reverse("smErp:index"))
        try:
            user = Account.account_manager.get(email__exact = email,passwd__exact = passwd)
        except (KeyError, Account.DoesNotExist):
            logger.error(u"没有对应的用户信息")
            return HttpResponseRedirect(reverse("smErp:index"))

        # todo : 判断用户是否已激活，如果没有激活，
        if not user.is_active:
            # 用户账号还没激活
            # 跳转到企业信息录入页面
            return HttpResponseRedirect(reverse("smErp:complete_company"))
        kwargs["user"]  = user
        kwargs["email"] = email
        return function_view(request, *args, **kwargs)
    return wrapped_view



@user_authenticate
def smErpManageView(request, *args, **kwargs):
    user = kwargs.get("user")
    # 用户的邮箱是否已经验证过
    try:
        email_vaild = user.email_vaild
        if not email_vaild:
            # 跳转到注册页面
            logger.error(u"用户[%s]未通过邮箱验证"%(user.email))
            return HttpResponseRedirect(reverse("smErp:register"))
    except Exception, e:
        logger.error(u"用户未登录异常:%s-e:%s"%(user, e.message), exc_info=True)
        return HttpResponseRedirect(reverse("smErp:index"))

    # company_status = user.
    brand_list = user.smerpbrand_set.all()
    # print brand_list
    product_list = user.smerpproduct_set.all()
    # 用户的企业信息
    # try:
    #     smErpInfo = SmerpErpinfo.erpinfo_manage.get(account_id = user.id)
    # except (KeyError, SmerpErpinfo.DoesNotExist):
    #     logger.error(u"用户[%s]还没完善企业资料"%(account))
    #     跳转到完善企业信息页面
        # return HttpResponseRedirect(reverse("smErp:complete_company"))
    smErpInfo = SmerpErpinfo.erpinfo_manage.filter(account_id = user.id)
    if not smErpInfo :
        logger.error(u"用户[%s]还没完善企业资料"%(account))
        # 跳转到完善企业信息页面
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    # company_status = user.smerperpinfo_set.all()[0].check_status
    company_status = smErpInfo.first().check_status
    # for order in user.smerpsmcodeorders.all():
    #     # print SmerpSmcode.smcode_manage.get(smerpsmcodeorder_id = order.order_id)
    #     try:
    #         print order.smerpsmcode
    #     except:
    #         logger.error("",exc_info=True)

    smcode_product_dict = {}
    # for smcode in user.smerpsmcodeorders.all():
    #     _product = smcode.smerpproduct
    #     if _product.check_status != 2 or _product.brand.check_status != 2:
    #         continue
    #
    #     pid = _product.id
    #     print pid
    #     publish_num = smcode.publish_num            # 已发布的数量
    #     num = int(smcode.num)                       # 购买的数量 todo: 数据库中是用的是字符串
    #     publish_end_no = smcode.publish_end_no      # 已经发布的结束码
    #     if pid not in smcode_product_dict:
    #         start_no = smcode.start_no
    #         if num > publish_num:
    #             smcode_product_dict[pid] = {"product_id": pid, "product_name": _product.name,
    #                                         "start_no": publish_end_no , "residue": num-publish_num }
    #     else:
    #         if num > publish_num:
    #             if publish_end_no < smcode_product_dict[pid]["start_no"]:
    #                 smcode_product_dict[pid]["start_no"] = publish_end_no
    #             smcode_product_dict[pid]["residue"] +=  (num - publish_num)
    # print smcode_product_dict
    suma_product_list = []
    for pd in user.smerpproduct_set.all():
        if str(pd.brand.check_status) == "2" and str(pd.check_status) == "2":
            suma_product_list.append(pd)

    # print company_status
    return render(request, "smErp/manage_new.html",{"user_info": user, "company_status": company_status, "suma_product_list": suma_product_list,
                                                 "smcode_product_list": smcode_product_dict.values()})


@user_authenticate
def smErpManageBrand(request, *args, **kwargs):
    """
    获取用户的品牌列表
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    user = kwargs.get("user")
    if request.method == "GET":
        return render(request, "smErp/brand_manage.html",{"user_info": user})
    elif request.method == "POST":
        brand_obj_list = user.smerpbrand_set.all()
        # 剩余能创建品牌个数
        can_brand_nums = config.BRAND_NUMS - len(brand_obj_list)
        if can_brand_nums < 0 :
            can_brand_nums = 0

        ret = config.getErrInfo("Success")
        brand_list = []
        for brand in brand_obj_list:
            brand_dict = model_to_dict(brand)
            brand_dict["check_status"] = brand.get_check_status_display()
            brand_list.append(brand_dict)
        ret["brand_list"] = brand_list
        ret["can_brand_nums"] = can_brand_nums
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")



@user_authenticate
def smErpManageProduct(request, *args, **kwargs):
    """
    获取用户的产品列表
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    user = kwargs.get("user")
    if request.method == "GET":
        return render(request, "smErp/product_manage.html",{"user_info": user})
    if request.method == "POST":
        product_obj_list = user.smerpproduct_set.all()
        # 剩余能创建产品个数
        can_product_nums = config.PRODUCT_NUMS - len(product_obj_list)
        if can_product_nums < 0 :
            can_product_nums = 0

        ret = config.getErrInfo("Success")
        product_list = []
        for product in product_obj_list:
            product_dict = model_to_dict(product)
            brand = product.brand
            product_dict["brandname"] = brand.name_zh
            product_dict["check_status"] = product.get_check_status_display()
            product_list.append(product_dict)
        ret["product_list"] = product_list
        ret["can_product_nums"] = can_product_nums
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")

    # 产品管理页面渲染
    elif request.method == "GET":
        suma_product_list = []
        for pd in user.smerpproduct_set.all():
            if str(pd.brand.check_status) == "2" and str(pd.check_status) == "2":
                suma_product_list.append(pd)

        return render(request, "smErp/suma_manage.html",{"user_info": user, "suma_product_list": suma_product_list})

@user_authenticate
def smErpManageMaterial(request, *args, **kwargs):
    """
    原料列表
    :param request:
    :return:
    """
    user = kwargs.get("user")
    if request.method == "GET":
        return render(request, "smErp/material_manage.html",{"user_info": user})
    elif request.method == "POST":
        material_obj_list = user.smerpmaterial_set.all()
        # 剩余能创建原料个数
        can_material_nums = config.PRODUCT_NUMS - len(material_obj_list)
        if can_material_nums < 0 :
            can_material_nums = 0

        ret = config.getErrInfo("Success")
        material_list = []
        for material in material_obj_list:
            material_dict = model_to_dict(material)
            # brand = material.brand
            # product_dict["brandname"] = brand.name_zh
            material_list.append(material_dict)
        ret["material_list"] = material_list
        ret["can_material_nums"] = can_material_nums
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")




# 进行模板拆分
@user_authenticate
def smErpManageSumaManageView(request, *args, **kwargs):
    user = kwargs.get("user")
    if request.method == "GET":
        suma_product_list = []
        for pd in user.smerpproduct_set.all():
            if str(pd.brand.check_status) == "2" and str(pd.check_status) == "2":
                suma_product_list.append(pd)

        return render(request, "smErp/suma_manage.html",{"user_info": user, "suma_product_list": suma_product_list, "price": config.SUMA_PRICE})


@user_authenticate
def smErpBrandInfo(request, brandid, *args, **kwargs):
    # print brandid
    # 查找到对应的brand
    # 校验对应的用户是否有查看的权限
    # 生成视图
    user = kwargs.get("user")
    email = kwargs.get("email")
    try:
        brand = user.smerpbrand_set.get(pk=brandid)
    except(KeyError, Brand.DoesNotExist):
        logger.error(u"不存在该品牌[%s]"%(brandid))
        return HttpResponseRedirect(reverse("smErp:index"))
    # 判断当前品牌是否为本用户的
    # if user.id != brand.account_id:
    #     logger.error(u"当前登录用户[%s]不是该品牌[%s]的拥有者"%(user.email, brandid))
    #     return HttpResponseRedirect(reverse("smErp:index"))
    if request.method == "GET":
        print brand.license_img_as_list()
        return render(request, "smErp/brand_info.html",{"brand": brand, "user_info": user})
    else:
        # pass
        action = request.POST.get("action","")
        if action == "delete":
            # 删除此品牌的相关信息
            brand.delete()
            return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")
        else:
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")

@user_authenticate
def smErpBrandInfoChange(request, brandid, *args, **kwargs):
    """
    品牌信息修改
    """
    user = kwargs.get("user")
    email = user.email
    try:
        brand = user.smerpbrand_set.get(pk=brandid)
    except (KeyError, Brand.DoesNotExist):
        logger.error(u"不存在对应的品牌id[%s]信息"%(brandid))
        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == "GET":
        return render(request, "smErp/brand_change.html", {"brand": brand, "user_info": user})

    elif request.method == "POST":
        print brandid
        brand_form = BrandForm(request.POST)
        if brand_form.is_valid():
            # brand_info = {}
            # brand_info["id"] = brand.id
            brand.name_zh = brand_form.cleaned_data["name_zh"]
            if request.POST.get("logo", None):
                brand.logo = request.POST["logo"]
            license_img_list = request.POST.getlist("license_img",[])
            if license_img_list:
                brand.license_img = ",".join(license_img_list)
            brand.name_en = request.POST["name_en"]
            brand.check_status = 1
            brand.description = request.POST["description"]
            brand.save()
            logger.info(u"用户[%s]品牌id[%s]更新成功"%(email, brand.id))
            return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")


@user_authenticate
def smErpCreateProduct(request, *args, **kwargs):
    # brandid = Brand.brand_manage.get(pk=brandid)
    """
        创建产品，用户权限，用户有几个品牌，对应哪个品牌，关联
    """
    # 提交创建产品

    user = kwargs.get("user")
    email = kwargs.get("email")
    # 用户的企业信息是否已经通过审核
    try:
        smErpInfo = SmerpErpinfo.erpinfo_manage.get(account_id = user.id)
    except (KeyError, SmerpErpinfo.DoesNotExist):
        logger.error(u"用户[%s]对应的企业资料不存在"%(email))
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    # 判断企业资料是否已经审核通过
    if smErpInfo.check_status != 2:
        logger.error(u"用户[%s]的企业资料还未审核通过"%(email))
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == 'POST':
        # 将信息解析存入数据库中
        # print  request.POST
        brandid = request.POST.get("brandid","")
        if brandid:
            try:
                brand = Brand.brand_manage.get(pk=brandid)
            except(KeyError, Brand.DoesNotExist):
                logger.error(u"没有对应的品牌信息")
                return HttpResponse(json.dumps(config.getErrInfo("BrandidInfoError")), content_type="application/json")
            # else:
            # 判断品牌是否为用户的
            if brand.account_id != user.id :
                logger.error(u"用户[%s]不是品牌[%s]的所有者"%(email, brandid))
                return HttpResponse(json.dumps(config.getErrInfo("BrandAccountError")), content_type="application/json")

            # 将产品信息入库
            name = request.POST.get("name", "")
            type = request.POST.get("type","")
            function = request.POST.get("pfunction","")
            suitable = request.POST.get("suitable","")
            not_suitable = request.POST.get("not_suitable","")
            attention = request.POST.get("attention","")
            hotline = request.POST.get("hotline","")
            service_info = request.POST.get("service_info","")
            workflows = request.POST.get("workflows","")
            standard = request.POST.get("standard", "")
            standard_pic = request.POST.get("standard_pic","")
            product_img_list = request.POST.getlist("img",[])
            material_list = request.POST.getlist("material",[])

            if not ( name and product_img_list and type and function and suitable and not_suitable and attention
                     and service_info and workflows and standard and standard_pic and material_list):
                logger.error(u"产品的信息不完整")
                logger.error(("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s")%(name , product_img_list , type , function , suitable , not_suitable , attention
                     , service_info , workflows , standard , standard_pic , material_list))
                return HttpResponse(json.dumps(config.getErrInfo("ProductInfoError")), content_type="application/json")

            # 将信息入库
            product = Product(account_id = user.id, brand_id = brandid, name = name, check_status = 1,
                              type=type, function=function, suitable = suitable, not_suitable=not_suitable,
                              attention = attention, hotline = hotline, service_info = service_info, workflows=workflows,standard=standard,
                              standard_pic=standard_pic)
            product.save()
            print "产品id", product.id
            # 将产品图片入库
            for img in product_img_list:
                product_img = SmerpProductImg(product_id = product.id, img = img)
                product_img.save()

            # 原材料入库
            for material in material_list:
                ProductMaterial.product_material_manage.create(product_id = product.id, material_id = material)

            return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")
        else:
            ret = config.getErrInfo("BrandidInfoError")
            return HttpResponse(json.dumps(ret), content_type="application/json")

    elif request.method == "GET":
        # 判断用户的产品是否已经超过数量
        product_list = user.smerpproduct_set.all()
        if config.PRODUCT_NUMS <= len(product_list):
            logger.error(u"用户[%s]创建产品的数量[%s]已超过上限"%(email, len(product_list)))
            return HttpResponseRedirect(reverse("smErp:index"))

        product_types =  Product.PRODUCT_TYPE_CHOICES
        print user.smerpbrand_set.filter(check_status__exact = 2)
        return render(request, "smErp/create_product.html", {"user_info": user, "product_types": product_types})

    else:
        return HttpResponseRedirect(reverse("smErp:index"))


@user_authenticate
def smErpProductInfo(request, product_id, *args, **kwargs):
    """
    用户产品的详细信息
    :param request:
    :param product_id:
    :return:
    """
    user = kwargs.get("user")
    email = kwargs.get("email")
    # 产品信息
    try:
        product =  user.smerpproduct_set.get(pk = product_id)
    except(KeyError, Product.DoesNotExist):
        logger.error(u"用户[%s]不存在对应的产品[%s]"%(email, product_id))
        return HttpResponseRedirect(reverse("smErp:index"))
    # print  product.brand_id
    try:
        brand = user.smerpbrand_set.get(pk = product.brand_id)
    except(KeyError, Brand.DoesNotExist):
        logger.error(u"用户[%s]不存在对应的品牌[%s]"%(email, product.brand_id))
        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == "GET":
        return render(request, "smErp/product_info.html",{"product": product, "user_info": user, "brand": brand})
    elif request.method == "POST":
        action = request.POST.get("action","")
        if action == "delete":
            # 删除此品牌的相关信息:
            product.delete()
            return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")
        else:
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")


# def addPicture(request):
#     if request.method == 'POST':
#         form = PictureForm(request.POST, request.FILES)
#         if form.is_valid():
#             f = request.FILES["imagefile"]
#             parser = ImageFile.Parser()
#             for chunk in f.chunks():
#                 parser.feed(chunk)
#             img = parser.close()
#             # 在img被保存之前，可以进行图片的各种操作，在各种操作完成后，在进行一次写操作
#             img.save("yoursavepath")

@csrf_exempt # 木法子，只能不校验CSRF
def ImageUpload(request):
    """
        文件上传接口
    """

    # request.
    # request.header("Access-Control-Allow-Origin", "*")
    # request.set_header("Access-Control-Allow-Origin", "*")
    image = request.FILES.get('file')
    # print request.POST
    max_size = request.POST.get("max_size",0)
    height = request.POST.get("height","")
    width = request.POST.get("width","")

    if request.method == 'POST':
        image_filename = '%s_%s' % (int(time.time()), str(image).decode("utf-8"))  # 名字独特性使用时间戳添加名字
        logger.info("将要保存文件名为:%s" % (image_filename,))

        media_path = "smErp/static/smErp/media/upload"
        logger.info("保存文件名全路径:%s" % (os.path.abspath(media_path),))

        if not os.path.exists(media_path) or not os.path.isdir(media_path):
            os.makedirs(media_path)

        try:
            save_path = "%s/%s" % (media_path, image_filename,)
            # fp = open(save_path, 'wb')
            # s = image.read()
            # fp.write(s)
            # fp.close()
            parser = ImageFile.Parser()
            for chunk in image.chunks():
                parser.feed(chunk)
            img = parser.close()
            # 在保存前做处理
            im_size = len(img.im)           # 图片大小
            im_hg = img.height              # 图片高
            im_wd = img.width               # 图片宽
            if max_size and int(max_size) *1024 < im_size:
                logger.error(u"图片大小超出限制")
                ret = config.getErrInfo("ImageSizeError")
                ret["reason"] = ret["reason"].format(size= max_size)
                return HttpResponse(json.dumps(ret), content_type="application/json")

            if height and width:
                if int(height) != int(im_hg) or int(width) != int(im_wd):
                    logger.error(u"图片高宽不符合要求")
                    ret = config.getErrInfo("ImageHeightWidthError")
                    ret["reason"] = ret["reason"].format(height = height, width =width)
                    return HttpResponse(json.dumps(ret), content_type="application/json")

            img.save(save_path)
            img_url = "/static/smErp/media/upload/%s" % (image_filename,)
            ret = config.getErrInfo("Success")
            ret["img_url"] = img_url
        except:
            ret = config.getErrInfo("SystemError")
            logger.exception("",exc_info=True)

        return HttpResponse(json.dumps(ret), content_type="application/json")
    else:
        # 跳转到错误页面
        # ret = copy.deepcopy(config.ERROR_CODE_INFO[""])
        raise Http404("页面不存在")


@csrf_exempt # 木法子，只能不校验CSRF
def FileUpload(request):
    """
        文件上传接口
    """

    # request.
    # request.header("Access-Control-Allow-Origin", "*")
    # request.set_header("Access-Control-Allow-Origin", "*")
    _file = request.FILES.get('file')
    # print request.POST

    if request.method == 'POST':
        file_name = str(_file).decode("utf-8")
        save_filename = '%s_%s' % (int(time.time()), file_name)  # 名字独特性使用时间戳添加名字
        logger.info("将要保存文件名为:%s" % (save_filename,))

        media_path = "smErp/static/smErp/file/upload"
        logger.info("保存文件名全路径:%s" % (os.path.abspath(media_path),))

        if not os.path.exists(media_path) or not os.path.isdir(media_path):
            os.makedirs(media_path)

        try:
            save_path = "%s/%s" % (media_path, save_filename,)
            fp = open(save_path, 'wb')
            s = _file.read()
            fp.write(s)
            fp.close()
            file_url = "/static/smErp/file/upload/%s" % (save_filename,)
            ret = config.getErrInfo("Success")
            ret["filename"] = file_name
            ret["file_url"] = file_url
        except:
            ret = config.getErrInfo("SystemError")
            logger.exception("",exc_info=True)

        return HttpResponse(json.dumps(ret), content_type="application/json")
    else:
        # 跳转到错误页面
        # ret = copy.deepcopy(config.ERROR_CODE_INFO[""])
        raise Http404("页面不存在")


# `name_zh` varchar(64) NOT NULL COMMENT '品牌中文名称',
#   `name_en` varchar(64) DEFAULT NULL COMMENT '品牌英文名称',
#   `logo` varchar(128) DEFAULT NULL COMMENT '商标logo',
#   `license_img` varchar(128) DEFAULT NULL COMMENT '品牌商标注册证书图片',
#   `check_status` tinyint(6) NOT NULL DEFAULT '0' COMMENT '审核状态：0-初始状态，1-提交审核，2-审核通过，3-审核失败',
#   `description` varchar(1024) DEFAULT NULL COMMENT '品牌描述信息',
#   `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

class BrandForm(forms.Form):
    name_zh = forms.CharField(max_length=64)
    # logo = forms.CharField(max_length=128)
    # license_img = forms.CharField(max_length=128)
    # description = forms.CharField(max_length=)


# @login_required(login_url='/accounts/login/')
@user_authenticate
def smErpCreateBrand(request, *args, **kwargs):
    """
    创建品牌视图
    :param request:
    :return:
    """
    user = kwargs.get("user")
    email = kwargs.get("email")
    if request.method == "POST":
        # 验证提交的表单数据
        name_zh = request.POST.get("name_zh", "")
        name_en = request.POST.get("name_en", "")
        logo = request.POST.get("logo", "")
        license_img = request.POST.get("license_img","")
        description = request.POST.get("description", "")
        if name_zh and logo and license_img:
            # 判断名称是否已经存在
            _brand = None
            try:
                _brand = Brand.brand_manage.get(name_zh=name_zh)
            except (KeyError, Brand.DoesNotExist):
                logger.info(u"品牌名称:[%s]不存在"%(name_zh,))
            else:
                ret = config.getErrInfo("BrandNameRepeatError")
                return HttpResponse(json.dumps(ret), content_type="application/json")
            # todo 校验中英文名称
            brand = Brand.brand_manage.create(account_id=user.id, check_status=1, name_zh=name_zh,
                                              name_en=name_en,logo=logo,license_img=license_img, description=description)
            ret = copy.deepcopy(config.getErrInfo("Success"))
        else:
            logger.error(u"用户[%s]创建品牌信息填写不完整"%email)
            ret = config.getErrInfo("BrandInfoError")
        return HttpResponse(json.dumps(ret), content_type="application/json")
    elif request.method == "GET":

        # 用户的企业信息是否已经通过审核
        try:
            smErpInfo = SmerpErpinfo.erpinfo_manage.get(account_id = user.id)
        except (KeyError, SmerpErpinfo.DoesNotExist):
            logger.error(u"用户[%s]对应的企业资料不存在"%(email))
            return HttpResponseRedirect(reverse("smErp:complete_company"))

        # 判断企业资料是否已经审核通过
        if smErpInfo.check_status != 2:
            logger.error(u"用户[%s]的企业资料还未审核通过"%(email))
            return HttpResponseRedirect(reverse("smErp:complete_company"))

        # 判断用户的品牌是否已经超过数量
        brand_list = user.smerpbrand_set.all()
        if config.BRAND_NUMS <= len(brand_list):
            logger.error(u"用户[%s]创建品牌数[%s]已超过上限"%(email, len(brand_list)))
            raise Http404(u"页面不存在")

        return render(request, "smErp/create_brand.html",{"user_info": user})
    else:
        raise Http404(u"页面不存在")

class BrandLicenseForm(forms.Form):
    """
    品牌证书表单
    """
    name = forms.CharField(max_length=32)
    type = forms.IntegerField()



@user_authenticate
def smErpBrandLicense(request, brandid, *args, **kwargs):
    """
    品牌证书
    :param requset:
    :return:
    """
    user = kwargs.get("user")
    email = kwargs.get("email")
    try:
        brand = user.smerpbrand_set.get(pk=brandid)
    except (KeyError, Brand.DoesNotExist):
        logger.error(u"用户[%s]不存在对应的品牌[%s]"%(email, brandid), exc_info=True)

        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == "GET":
        if request.GET["action"] == "create":
            license_types = BrandLicense.TYPE_CHOIES
            return render(request, "smErp/brand_license_create.html", {"brand": brand, "license_types": license_types})
        if request.GET["action"] == "change":
            license_id = request.GET["license"]
            try:
                license = brand.smerpbrandlicense_set.get(pk=license_id)
            except (KeyError, BrandLicense.DoesNotExist):
                logger.error(u"品牌id[%s]的证书id[%s]信息已不存在"%(brandid, license_id))
                raise Http404(u"页面不存在")
            return render(request, "smErp/brand_license_change.html", {"user_info": user, "brand": brand, "license": license})

    elif request.method == "POST":
        if request.POST["action"] == "create":
            license_type = request.POST.get("type",0)
            img = request.POST.get("img","")
            type_tuple = [str(i[0]) for i in BrandLicense.TYPE_CHOIES]
            if license_type not in type_tuple or not img:
                logger.error(u"创建品牌[%s]证书，证书类型[%s]不能为空,证书图片[%s]不能为空"%(brandid, license_type, img))
                return config.getErrInfo("BrandLicenseTypeError")
            try:
                if license_type == "4":
                    # 其他类型证书，需要填写名称，描述，图片，图标(选填)
                    license_name = request.POST.get("name","")
                    description = request.POST.get("description","")
                    icon = request.POST.get("icon","")

                    if not (license_name and img):
                        logger.error(u"用户[%s]创建品牌其他证书[%s]，证书信息不完整"%(email, license_type))
                        return config.getErrInfo("BrandLicenseInfoError")
                    brand_license = BrandLicense(brand = brand)
                    brand_license.name = license_name
                    brand_license.type = license_type
                    brand_license.img = img
                    if description:
                        brand_license.description = description
                    if icon:
                        brand_license.icon = icon
                    brand_license.save()
                    # 将对应的品牌状态改为提交审核
                    # brand.check_status = 1
                    # brand.save()
                    # logger.info(u"用户[%s]创建品牌[%s]其他证书成功"%(email, brandid))
                else:
                    # 对应类型证书
                    license_name = ""
                    for t in BrandLicense.TYPE_CHOIES:
                        if str(t[0]) == license_type:
                            license_name = t[1]
                            break

                    print license_name
                    brand_license = BrandLicense(brand=brand, name=license_name,img=img, type=license_type, create_time=datetime.datetime.now())
                    brand_license.save()

                # 将对应的品牌状态改为提交审核
                brand.check_status = 1
                brand.save()
                logger.info(u"用户[%s]创建品牌[%s]其他证书成功"%(email, brandid))
                ret = config.getErrInfo("Success")
            except Exception, e:
                logger.error(u"添加品牌[%s]的证书失败msg: %s"%(brandid, e.message), exc_info=True)
                ret = config.getErrInfo("SystemError")

            # else:
            #     ret = config.getErrInfo("BrandLicenseInfoError")

            return HttpResponse(json.dumps(ret), content_type="application/json")

        elif request.POST["action"] == "change":
            license_id = request.POST["license"]
            try:
                brand_license = brand.smerpbrandlicense_set.get(pk=license_id)
            except (KeyError, BrandLicense.DoesNotExist):
                logger.error(u"品牌id[%s]的证书id[%s]信息已不存在"%(brandid, license_id), exc_info=True)
                raise Http404(u"页面不存在")
            try:
                # brand_license.brand_id = brand
                brand_license.name = request.POST["name"]
                brand_license.type = request.POST["type"]
                if request.POST.get("description",""):
                    brand_license.description = request.POST["description"]
                if request.POST.get("img",""):
                    brand_license.img = request.POST["img"]
                if request.POST.get("icon",""):
                    brand_license.icon = request.POST["icon"]
                brand_license.save()
                # 将对应的品牌状态改为提交审核
                brand.check_status = 1
                brand.save()
                ret = config.getErrInfo("Success")
            except Exception, e:
                logger.error(u"添加品牌[%s]的证书失败msg: %s"%(brandid, e.message), exc_info=True)
                ret = config.getErrInfo("SystemError")

            return HttpResponse(json.dumps(ret), content_type="application/json")

        elif request.POST["action"] == "delete":
            # print request.POST
            license_id = request.POST["license"]
            try:
                brand_license = brand.smerpbrandlicense_set.get(pk=license_id)
            except (KeyError, BrandLicense.DoesNotExist):
                logger.error(u"品牌id[%s]的证书id[%s]信息已不存在"%(brandid, license_id), exc_info=True)
                ret = config.getErrInfo("BrandLicenseNoExist")
            else:
                brand_license.delete()
            # 将对应的品牌状态改为提交审核
            brand.check_status = 1
            brand.save()
            ret = config.getErrInfo("Success")
            return HttpResponse(json.dumps(ret), content_type="application/json")


@user_authenticate
def smErpProductLicense(request, productid, *args, **kwargs):
    """
    品牌证书
    :param requset:
    :return:
    """
    user = kwargs.get("user")
    email = kwargs.get("email")

    # 判断当前品牌是否为本用户的
    try:
        product = user.smerpproduct_set.get(pk=productid)
    except(KeyError, Product.DoesNotExist):
        logger.error(u"当前登录用户[%s]不是该产品[%s]的拥有者"%(email, productid), exc_info=True)
        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == "GET":
        if request.GET["action"] == "create":
            license_types = ProductLicense.TYPE_CHOIES
            # 判断用户的品牌是否已经超过数量
            return render(request, "smErp/product_license_create.html", {"user_info": user, "product": product, "license_types": license_types})
        if request.GET["action"] == "change":
            license_id = request.GET["license"]
            try:
                license = product.smerpproductlicense_set.get(pk=license_id)
            except (KeyError, BrandLicense.DoesNotExist):
                logger.error(u"产品id[%s]的证书id[%s]信息已不存在"%(productid, license_id), exc_info=True)
                raise Http404(u"页面不存在")
            return render(request, "smErp/product_license_change.html", {"user_info": user, "product": product, "license": license})

    elif request.method == "POST":
        if request.POST["action"] == "create":
            try:
                license_type = request.POST.get("type","")
                img = request.POST.get("img","")
                type_tuple = [str(i[0]) for i in ProductLicense.TYPE_CHOIES]
                if license_type not in type_tuple or not img:
                    logger.error(u"创建品牌[%s]证书，证书类型[%s]不能为空,证书图片[%s]不能为空"%(brandid, license_type, img))
                    return config.getErrInfo("ProductLicenseTypeError")

                product_license = ProductLicense(product=product)
                if license_type == "4":
                    product_license.name = request.POST["name"]
                else:
                    product_license_name = ""
                    for i in ProductLicense.TYPE_CHOIES:
                        if str(i[0]) == license_type:
                            product_license_name = i[1]

                    product_license.name = product_license_name

                # product_license.name = request.POST["name"]
                product_license.type = license_type
                product_license.img = img
                if request.POST.get("effect_time", None) and request.POST.get("expire_time", None):
                    effect_time = request.POST["effect_time"]
                    expire_time = request.POST["expire_time"]
                    if effect_time >= expire_time:
                        logger.error(u"创建产品证书日期填写不正确")
                        ret = config.getErrInfo("ProductLicenseDateError")
                        return HttpResponse(json.dumps(ret), content_type="application/json")
                    # print effect_time, "//", expire_time
                    product_license.effect_time = datetime.datetime.strptime(effect_time, "%Y-%m-%d").strftime("%Y-%m-%dT%H:%M:%S.%fZ")
                    product_license.expire_time = datetime.datetime.strptime(expire_time, "%Y-%m-%d").strftime("%Y-%m-%dT%H:%M:%S.%fZ")
                else:
                    logger.error(u"创建产品证书日期填写不完整")
                    raise KeyError
                product_license.save()
                # 产品状态改为未提交
                product.check_status = 0
                product.save()
                ret = config.getErrInfo("Success")
            except Exception, e:
                logger.error(u"创建产品证书信息[%s], 异常：%s"%(productid, e.message), exc_info=True)
                ret = config.getErrInfo("ProductLicenseInfoError")

            return HttpResponse(json.dumps(ret), content_type="application/json")

        elif request.POST["action"] == "change":
            license_id = request.POST["license"]
            try:
                product_license = product.smerpproductlicense_set.get(pk=license_id)
            except (KeyError, ProductLicense.DoesNotExist):
                logger.error(u"产品id[%s]的证书id[%s]信息已不存在"%(productid, license_id), exc_info=True)
                raise Http404(u"页面不存在")
            try:
                if request.POST.get("name", ""):
                    product_license.name = request.POST["name"]
                if request.POST.get("type",""):
                    product_license.type = request.POST["type"]
                if request.POST.get("img",""):
                    product_license.img = request.POST["img"]
                if request.POST.get("effect_time",""):
                    product_license.effect_time = request.POST["effect_time"]
                if request.POST.get("expire_time",""):
                    product_license.effect_time = request.POST["expire_time"]
                product_license.save()
                # 将产品的状态更新为待审核
                product.check_status = 1
                product.save()
                ret = config.getErrInfo("Success")
            except Exception, e:
                logger.error(u"添加产品[%s]的证书失败msg: %s"%(productid, e.message), exc_info=True)
                ret = config.getErrInfo("SystemError")

            return HttpResponse(json.dumps(ret), content_type="application/json")

        elif request.POST["action"] == "delete":
            # print request.POST
            license_id = request.POST.get("license","")
            try:
                product_license = product.smerpproductlicense_set.get(pk=license_id)
            except (KeyError, Product.DoesNotExist):
                logger.error(u"产品id[%s]的证书id[%s]信息已不存在"%(productid, license_id), exc_info=True)
                ret = config.getErrInfo("ProductLicenseNoExist")
            else:
                product_license.delete()
                # 更新产品状态
                product.check_status = 0
                product.save()
                ret = config.getErrInfo("Success")
            return HttpResponse(json.dumps(ret), content_type="application/json")

@user_authenticate
def smErpCreateMaterial(request, *args, **kwargs):
    """
    创建品牌视图
    :param request:
    :return:
    """
    user = kwargs.get("user")
    email = kwargs.get("email")
    smErpInfo = user.smerperpinfo_set.all().first()
    if not smErpInfo:
        logger.error(u"用户[%s]没有企业信息"%(email))
        return HttpResponseRedirect(reverse("smErp:complete_company"))
    # 判断企业资料是否已经审核通过
    if smErpInfo.check_status != 2:
        logger.error(u"用户[%s]的企业资料还未审核通过"%(email))
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == "POST":
        name = request.POST.get("name","")
        producer = request.POST.get("producer","")
        source_type = request.POST.get("source_type","")
        ref_image = request.POST.get("ref_image","")
        ref_url = request.POST.get("ref_url","")
        print name , producer , source_type , ref_image , ref_url
        if not (name and producer and source_type and ref_image and ref_url):
            logger.error(u"用户[%s]创建原料的填写信息不全"%email)
            ret = config.getErrInfo("MaterialInfoError")
        else:
            material_info = {"account_id": user.id, "name": name, "producer": producer, "source_type": source_type, "ref_image": ref_image, "ref_url": ref_url}
            SmerpMaterial.material_manage.create(**material_info)
            ret = copy.deepcopy(config.getErrInfo("Success"))
        return HttpResponse(json.dumps(ret), content_type="application/json")
    elif request.method == "GET":
        # # 用户的企业信息是否已经通过审核
        # try:
        #     smErpInfo = SmerpErpinfo.erpinfo_manage.get(account_id = user.id)
        # except (KeyError, SmerpErpinfo.DoesNotExist):
        #     logger.error(u"用户[%s]对应的企业资料不存在"%(email))
        #     raise Http404(u"页面不存在")
        #
        # # 判断企业资料是否已经审核通过
        # if smErpInfo.check_status != 2:
        #     logger.error(u"用户[%s]的企业资料还未审核通过"%(email))
        #     raise Http404(u"页面不存在")
        material_list = user.smerpmaterial_set.all()
        # 判断用户的原料是否已经超过数量
        can_material_nums = config.MATERIAL_NUMS - len(material_list)
        if can_material_nums <= 0 :
            raise Http404(u"页面不存在")
        return render(request, "smErp/create_material.html",{"user_info": user})
    else:
        raise Http404("页面不存在")


def smErpProductInfoChange(request, product_id):
    """
    产品信息修改
    """

    email = request.session.get("email", "")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    # 查找当前用户信息
    # user = get_object_or_404(Account, email=email, passwd=passwd)
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd), exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))
    try:
        product = user.smerpproduct_set.get(pk=product_id)
    except(KeyError, Product.DoesNotExist):
        logger.error(u"用户[%s]不是产品[%s]的所有者"%(email, product_id), exc_info=True)
        return HttpResponseRedirect(reverse("smErp:index"))

    if request.method == "GET":
        product_types = Product.PRODUCT_TYPE_CHOICES
        product_materials = product.smerpproductmaterial_set.all()
        product_material_ids = []
        for m in product_materials:
            product_material_ids.append(m.material_id)
        return render(request, "smErp/product_change.html", {"product": product, "user_info": user, "product_types": product_types, "product_material_ids": product_material_ids})

    elif request.method == "POST":
        # print product_id
        try:
            if request.POST.get("name",""):
                product.name = request.POST.get("name","")
            if request.POST.get("type",""):
                product.type = request.POST.get("type","")
            if request.POST.get("pfunction",""):
                product.function = request.POST.get("pfunction","")
            if request.POST.get("suitable",""):
                product.suitable = request.POST.get("suitable","")
            if request.POST.get("not_suitable",""):
                product.not_suitable = request.POST.get("not_suitable","")
            if request.POST.get("attention",""):
                product.attention = request.POST.get("attention","")
            if request.POST.get("hotline",""):
                product.hotline = request.POST.get("hotline","")
            if request.POST.get("service_info",""):
                product.service_info = request.POST.get("service_info","")
            if request.POST.get("standard",""):
                product.standard = request.POST.get("standard","")
            if request.POST.get("workflows",""):
                product.workflows = request.POST.get("workflows","")
            if request.POST.get("standard_pic",""):
                product.standard_pic = request.POST.get("standard_pic","")

            if request.POST.get("img", None):
                # 删除以前的图片
                smErpProduct_imgs = product.smerpproductimg_set.all()
                # print smErpProduct_imgs
                for img in smErpProduct_imgs:
                    img.delete()
                new_imgs = request.POST.getlist("img", [])
                # if new_imgs:
                #     raise KeyError
                for img_url in new_imgs:
                    product_img = SmerpProductImg(product_id = product_id, img = img_url)
                    product_img.save()
            # 更改原料
            if request.POST.getlist("material",[]):
                # 原始原料列表
                old_material = product.smerpproductmaterial_set.all()
                old_material_ids = []
                for om in old_material:
                    old_material_ids.append(int(om.material_id))

                for mid in request.POST.getlist("material",[]):
                    if int(mid) in old_material_ids:
                        old_material_ids.remove(int(mid))
                        continue
                    material = ProductMaterial(product_id = product.id, material_id = mid)
                    material.save()

                # 剔除原来的原料关系
                smErpProductMaterials = product.smerpproductmaterial_set.all()
                for material in smErpProductMaterials:
                    if material.material_id in old_material_ids:
                        material.delete()

            product.check_status = 1
            product.save()
            ret = config.getErrInfo("Success")
            return HttpResponse(json.dumps(ret), content_type="application/json")
            # try:
        except Exception, e:
            logger.error(u"修改产品信息失败-%s"%e.message, exc_info=True)
            return HttpResponse(json.dumps(config.getErrInfo("SystemError")), content_type="application/json")



def test(request):
    context = {}
    return render(request, "smErp/testdemo.html", context=context)


def index(request):
    context = {}
    return render(request, "smErp/index.html", context=context)


def resource(request):
    email = request.session.get("email",None)
    passwd = request.session.get("passwd", None)

    try:
        user = Account.account_manager.get(email=email, passwd=passwd, is_active = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd), exc_info=True)
        user = None

    context = {"user_info": user}
    return render(request, "smErp/resource.html", context=context)


def manage(request):
    context = {}
    return render(request, "smErp/manage.html", context=context)

@user_authenticate
def statistics(request, *args, **kwargs):
    user = kwargs.get("user")
    # 用户的邮箱是否已经验证过
    try:
        email_vaild = user.email_vaild
        if not email_vaild:
            # 跳转到注册页面
            logger.error(u"用户[%s]未通过邮箱验证"%(user.email))
            return HttpResponseRedirect(reverse("smErp:register"))
    except Exception, e:
        logger.error(u"用户未登录异常:%s-e:%s"%(user, e.message), exc_info=True)
        return HttpResponseRedirect(reverse("smErp:index"))
    email = user.email
    if request.method == "GET":
        # 如果用户还未激活，跳转到企业信息页面
        if not user.is_active:
            logger.error(u"用户[%s]账号还未审核通过"%email)
            return HttpResponseRedirect(reverse("smErp:complete_company"))
        # 用户的企业信息
        try:
            company_info = SmerpErpinfo.erpinfo_manage.get(account_id__exact=user.id)
        except (KeyError, SmerpErpinfo.DoesNotExist):
            logger.error(u"用户[%s]还没有对应的企业信息"%(email), exc_info=True)
            return HttpResponseRedirect(reverse("smErp:complete_company"))

        context = {"user_info": user}
        return render(request, "smErp/statistics.html", context=context)

@user_authenticate
def account(request, *args, **kwargs):
    """
    账号中心
    :param request:
    :return:
    """
    user = kwargs.get("user")
    # 用户的邮箱是否已经验证过
    try:
        email_vaild = user.email_vaild
        if not email_vaild:
            # 跳转到注册页面
            logger.error(u"用户[%s]未通过邮箱验证"%(user.email))
            return HttpResponseRedirect(reverse("smErp:register"))
    except Exception, e:
        logger.error(u"用户未登录异常:%s-e:%s"%(user, e.message), exc_info=True)
        return HttpResponseRedirect(reverse("smErp:index"))
    email = user.email
    if request.method == "GET":
        # email = request.session.get('email', "")
        # passwd = request.session.get('passwd', "")
        # if not (email and passwd):
        #     logger.error(u"用户[%s][%s]未登录"%(email, passwd))
        #     return HttpResponseRedirect(reverse("smErp:index"))
        #
        # try:
        #     user = Account.account_manager.get(email__exact = email, passwd__exact = passwd, email_vaild__exact = 1)
        # except (KeyError, Account.DoesNotExist):
        #     logger.error(u"没有对应的用户[%s]信息"%(email), exc_info=True)
        #     return HttpResponseRedirect(reverse("smErp:index"))
        # 用户的企业信息
        try:
            company_info = SmerpErpinfo.erpinfo_manage.get(account_id__exact=user.id)
        except (KeyError, SmerpErpinfo.DoesNotExist):
            logger.error(u"用户[%s]还没有对应的企业信息"%(email), exc_info=True)
            return HttpResponseRedirect(reverse("smErp:complete_company"))

        context = {"user_info": user, "company_info": company_info}
        return render(request, "smErp/account.html", context=context)


def smErpSumaOrder(request):
    """
    溯码下单接口
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    # user = get_object_or_404(Account, email=email, passwd=passwd)
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd), exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == "POST":
        # 对应的产品
        product_id = request.POST.get("product_id","")
        sm_num = int(request.POST.get("suma_num",0))
        if not (product_id and sm_num):
            logger.error(u"提交溯码订单信息不完整：pid-%s, sm_num-%s"%(product_id, sm_num))
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")

        try:
            product = user.smerpproduct_set.get(pk=product_id)
        except(KeyError, Product.DoesNotExist):
            logger.error(u"用户[%s]不是产品[%s]的所有者"%(email, product_id), exc_info=True)
            ret = config.getErrInfo("ProductError")
        else:
            order_id = "%s%s%s"%(user.id, product_id, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
            sm_code_order = SmerpSmcodeOrder(order_id = order_id, account_id = user.id, product_id = product_id, num = sm_num, add_code_status = 0)
            sm_code_order.goods_desc = u"%s份%s溯码"%( sm_num,product.name)
            sm_code_order.goods_amount = sm_num * 100
            sm_code_order.pay_type = ""
            sm_code_order.pay_status = 0
            sm_code_order.create_time = datetime.datetime.now()
            sm_code_order.save()
            logger.info(u"产品[%s]溯码下单[%s]份成功"%(product_id, sm_num))
            ret = config.getErrInfo("Success")
        return HttpResponse(json.dumps(ret), content_type="application/json")


def smErpSumaOrderList(request):
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    # user = get_object_or_404(Account, email=email, passwd=passwd)
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd), exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))
    if request.method == "POST":
        print request.POST
        order_list = []
        for order in user.smerpsmcodeorders.all():
            # print dir(order)
            data = {}
            data["order_id"] = order.order_id
            data["product_name"] = order.product.name
            try:
                smcode = order.smerpsmcode
            except(KeyError, SmerpSmcode.DoesNotExist):
                logger.error("",exc_info=True)
                data["start_num"] = ""
                data["end_num"] = ""
            else:
                data["start_num"] = smcode.start_no
                data["end_num"] = smcode.end_no

            if order.pay_status == 2 and order.add_code_status == 2:
                data["order_status"] = 2        # 可以下载
            elif order.pay_status == 2:
                data["order_status"] = 1        # 支付了
            else:
                data["order_status"] = 0        # 没有支付
            data["numbers"] = order.num
            data["ctime"] = order.create_time
            order_list.append(data)

        ret = {"data": order_list}
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")


def smErpMaterialChange(request):
    # pass
    """
    修改原料信息
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd),exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == "POST":
        # 确认原料的想属于该用户
        material_id = request.POST.get("pk", "")
        try:
            material = user.smerpmaterial_set.get(pk=material_id)
        except(KeyError, SmerpMaterial.DoesNotExist):
            logger.error(u"原料[%s]不属于用户[%s]"%(material_id, email), exc_info=True)
            # ret = config.ERROR_CODE_INFO["MaterialNotUserError"]
            return HttpResponse(json.dumps(config.getErrInfo("MaterialNotUserError")), content_type="application/json")
        #
        # print request.POST
        # 更新的字段
        field = request.POST.get("name", "")
        value = request.POST.get("value","")
        if not (field and value):
            logger.error(u"修改原料信息参数错误")
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")
        try:
            data_dict = {field: value, "create_time": datetime.datetime.now()}
            Material.material_manage.filter(pk=material_id).update(**data_dict)
            # material.save()
        except Exception, e:
            logger.error(u"修改原料[%s]信息发生异常: %s"%(material_id, e.message), exc_info=True)
            return HttpResponse(json.dumps(config.getErrInfo("SystemError")), content_type="application/json")

        ret = config.getErrInfo("Success")
        return HttpResponse(json.dumps(ret), content_type="application/json")



def smErpSumaPublish(request):
    """
    发布溯码
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd),exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == "POST":
        product_id = int(request.POST.get("product_id",0))
        try:
            product = user.smerpproduct_set.get(pk=product_id)
        except(KeyError, Product.DoesNotExist):
            logger.error(u"用户[%s]输入的产品[%s]不存在"%(email, product_id))
            return HttpResponseRedirect(reverse("smErp:index"))

        number = int(request.POST.get("number",0))
        try:
            price = int(float(request.POST.get("price",0)) * 100)
        except:
            logger.error(u"输入的建议价格格式不正确：%s"%(request.POST.get("price")), exec_info=True)
            return HttpResponse(json.dumps(config.getErrInfo("SumaPublishPriceError")), content_type="application/json")

        area = request.POST.get("area","")
        if not (number and price and area):
            logger.error(u"溯码发布缺少必要参数")
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")

        # 增加一条发布记录
        # 确定溯码订单的扣除
        smcode_start_no = 0
        smcode_end_no = 0
        _number = number
        # smcode_list = user.smerpsmcodes.all().order_by('id')
        smcode_list = user.smerpaccountcodes.all().order_by("id")
        print smcode_list
        for smcode in smcode_list:
            _product = smcode.smerpproduct
            if _product.id == product_id:
                publish_num = int(smcode.publish_num)
                num = int(smcode.num)
                if publish_num < num:
                    _start_no = smcode.publish_end_no
                    if smcode_start_no == 0:
                        smcode_start_no = _start_no

                    if(num - publish_num > number):
                        # 更新当前订单信息
                        smcode.publish_end_no = smcode.publish_end_no + number
                        smcode.publish_num = publish_num + number
                        smcode.save()
                        smcode_end_no = smcode_start_no + number
                        break
                    else:
                        smcode.publish_end_no = smcode.end_no
                        smcode.publish_num = num
                        smcode.save()
                        number = number - (num - publish_num)
        #       id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        # `account_id` bigint(20) NOT NULL COMMENT '账号id',
        # `product_id` bigint(20) NOT NULL COMMENT '产品Id',
        # `num` bigint(20) NOT NULL COMMENT '数量',
        # `start_no` bigint(20) NOT NULL COMMENT '开始号段',
        # `end_no` bigint(20) NOT NULL COMMENT '结束号段',
        # `price` float NOT NULL COMMENT '建议售价',
        # `province` varchar(64) NOT NULL COMMENT '发布省份',
        # `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
        # 增加一条发布记录
        SmerpPublishSmcodeLog.sm_publish_manage.create(smerpaccount=user, smerpproduct= product,
                                                       num=_number, start_no=smcode_start_no, end_no = smcode_end_no,
                                                       price = price, province=area, create_time = datetime.datetime.now())
        return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")



def smErpSumaPublishList(request):
    """
    发布的溯码订单信息
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    # user = get_object_or_404(Account, email=email, passwd=passwd)
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd), exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == "POST":
        # print request.POST
        publish_log_list = []
        for publish_log in user.smerppublishsmcodelogs.all():
            data = {}
            data["product_name"] = publish_log.smerpproduct.name
            data["num"] = publish_log.num
            data["start_no"] = publish_log.start_no
            data["end_no"] = publish_log.end_no
            data["price"] = str(int(publish_log.price) * 1.0 / 100)
            data["province"] = publish_log.province
            data["create_time"] = publish_log.create_time
            publish_log_list.append(data)

        ret = {"data": publish_log_list}
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")



def smErpSumaProductList(request):
    """
    拉取溯码产品信息列表
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd),exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))

    if request.method == "POST":
        smcode_product_dict = {}
        for smcode in user.smerpaccountcodes.all():
            _product = smcode.smerpproduct
            if _product.check_status != 2 or _product.brand.check_status != 2:
                continue

            pid = _product.id
            # print pid
            publish_num = smcode.publish_num            # 已发布的数量
            num = int(smcode.num)                       # 购买的数量 todo: 数据库中是用的是字符串
            publish_end_no = smcode.publish_end_no      # 已经发布的结束码
            if pid not in smcode_product_dict:
                start_no = smcode.start_no
                if num > publish_num:
                    smcode_product_dict[pid] = {"product_id": pid, "product_name": _product.name,
                                                "start_no": publish_end_no + 1 , "residue": num-publish_num }
            else:
                if num > publish_num:
                    if publish_end_no < smcode_product_dict[pid]["start_no"]:
                        smcode_product_dict[pid]["start_no"] = publish_end_no + 1
                    smcode_product_dict[pid]["residue"] +=  (num - publish_num)

        ret = copy.deepcopy(config.getErrInfo("Success"))
        ret["smcode_product_list"] = smcode_product_dict.values()
        return HttpResponse(json.dumps(ret), content_type="application/json")


def smErpSumaScanCodeList(request):
    """
    溯码扫描记录
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd),exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))
    if request.method == "POST":
        # print [id['id'] for id in user.smerpproduct_set.all().values("id")]
        scan_logs = []
        scan_models_logs = WxmpScanLog.wxmp_scan_log_manage.filter(product_id__in = [id['id'] for id in user.smerpproduct_set.all().values("id")])
        for scan_log in scan_models_logs:
            scan_logs.append(model_to_dict(scan_log))
        ret = {"data": scan_logs}
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")

def smErpSumaScanAbnormalList(request):
    """
    异常记录列表
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd),exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))
    if request.method == "POST":
        # print [id['id'] for id in user.smerpproduct_set.all().values("id")]
        abnormal_logs = []
        abnormal_models_logs = WxmpAbnormalLog.wxmp_abnormal_manage.filter(product_id__in = [id['id'] for id in user.smerpproduct_set.all().values("id")])
        for abnormal_log in abnormal_models_logs:
            type_ch = abnormal_log.get_type_display()
            abnormal = model_to_dict(abnormal_log)
            abnormal.update({"type_ch": type_ch})
            abnormal_logs.append(abnormal)

        # print abnormal_logs
        ret = {"data": abnormal_logs}
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")


def smErpSumaScanFeedback(request):
    """
    用户反馈记录
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    if not (email and passwd):
        logger.error(u"用户的登录信息[%s][%s]不存在"%(email, passwd))
        return HttpResponseRedirect(reverse("smErp:index"))
    try:
        user = Account.account_manager.get(email=email, passwd=passwd, email_vaild__exact = 1)
    except (KeyError, Account.DoesNotExist):
        logger.error(u"用户[%s]验证失败[%s]"%(email, passwd),exc_info=True)
        # 跳转首页
        return HttpResponseRedirect(reverse("smErp:index"))
    # 如果用户还未激活，跳转到企业信息页面
    if not user.is_active:
        logger.error(u"用户[%s]账号还未审核通过"%email)
        return HttpResponseRedirect(reverse("smErp:complete_company"))
    if request.method == "POST":
        # print [id['id'] for id in user.smerpproduct_set.all().values("id")]
        feedback_logs = []
        feedback_models_logs = WxmpFeedback.wxmp_feedback_manage.filter(product_id__in = [id['id'] for id in user.smerpproduct_set.all().values("id")])
        for feedback_log in feedback_models_logs:
            feedback = model_to_dict(feedback_log)
            feedback["product_name"] = feedback_log.product.name
            feedback_logs.append(feedback)
        ret = {"data": feedback_logs}
        return HttpResponse(json.dumps(ret, cls=SMJsonEncoder), content_type="application/json")




def ChangePassword(request):
    """
    修改用户密码
    :param request:
    :return:
    """
    email = request.session.get("email","")
    passwd = request.session.get("passwd", "")
    user = get_object_or_404(Account, email=email, passwd=passwd)
    if request.method == "POST":
        # 校验输入的原始密码是否正确
        old_password = request.POST.get("old_password","")
        _md5pwd = hashlib.md5("%s%s"%(old_password, config.PASSWORD_KEY)).hexdigest()
        if _md5pwd != user.passwd:
            logger.error(u"用户[%s]修改密码，输入的原始密码不正确, _md5pwd[%s], passwd[%s]"%(email, _md5pwd, passwd))
            return HttpResponse(json.dumps(config.getErrInfo("PasswordError")), content_type="application/json")
        # 更新用户密码
        new_password = request.POST.get("new_password","")
        if len(new_password) < 8:
            logger.error(u"用户[%s]输入的新密码位数不对"%(email))
            return HttpResponse(json.dumps(config.getErrInfo("NewPasswordError")), content_type="application/json")
        confirm_password = request.POST.get("confirm_password","")
        if confirm_password != new_password:
            logger.error(u"用户[%s]重置密码两次输入密码不相同"%(email))
            return HttpResponse(json.dumps(config.getErrInfo("NewPasswordError")), content_type="application/json")

        _md5pwd = hashlib.md5("%s%s"%(new_password, config.PASSWORD_KEY)).hexdigest()
        user.passwd = _md5pwd
        user.save()
        # 清楚cookie
        del request.session["email"]
        del request.session["passwd"]
        return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")

@csrf_exempt
def CreateSumaView(request):
    """
    生成溯码
    1、将对应的溯码订单生成对应的溯码范围
    :param request:
    :return:
    """
    # print request.method
    order_id = request.GET.get("orderid","")
    product_id = request.GET.get("productid","")
    bank_id = request.GET.get("bankid","")
    if not (order_id and product_id and bank_id):
        logger.error(u"生成溯码，参数错误")
        return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json")

    try:
        product = Product.product_manage.get(pk=product_id)
    except(KeyError, Product.DoesNotExist):
        logger.error(u"对应的产品[%s]不存在"%(product_id))
        return HttpResponse(json.dumps(config.getErrInfo("ProductError")), content_type="application/json")

    try:
        order = product.smerpsmcodeorders.get(order_id=order_id)
    except(KeyError, SmerpSmcodeOrder.DoesNotExist):
        logger.error(u"产品[%s]对应的订单[%s]不存在"%(product_id, order_id))
        return HttpResponse(json.dumps(config.getErrInfo("SumaOrderError")), content_type="application/json")
    # print product, order
    add_code_status = order.add_code_status
    pay_status = order.pay_status
    if add_code_status == 2:
        logger.error(u"该订单[%s]已经处理过"%(order_id))
        return HttpResponse(json.dumps(config.getErrInfo("SumaOrderDealedError")), content_type="application/json")
    # 处理订单
    # 将订单支付状态置为已支付
    if pay_status != 2:
        order.pay_status = 2
        order.save()

    # 生成溯码
    smcode_log = None
    try:
        smcode_log = order.smerpsmcode
    except (KeyError, SmerpSmcode.DoesNotExist):
        logger.error("没有对应的溯码记录",exc_info=True)
    else:
        logger.error(u"溯码订单[%s]已处理过"%(order_id))
        return HttpResponse(json.dumps(config.getErrInfo("SumaOrderDealedError")), content_type="application/json")
    if not smcode_log:
        # 生成溯码
        # 数据库中该产品的所有溯码订单
        product_smcodes = SmerpSmcode.smcode_manage.filter(smerpproduct_id = product_id).order_by('end_no')

        if product_smcodes.first():
            smcode_int = product_smcodes.first().end_no
            # 取溯码位数
            # smcode = str(end_smcode_no)[6:]
            # 转成整数
            # smcode_int = int(smcode, 16)
        else:
            smcode_int = 0

        # 该订单起始溯码
        # smcode_start_no = hex(smcode_int + 1)
        # 补齐
        # start_smcode_no = ("0"*10 + smcode_start_no.lstrip("0x"))[-10:].upper()
        # 该订单结束溯码
        num = int(order.num)
        smcode_end_int = smcode_int + num
        # smcode_end_no = hex(smcode_end_int)
        # 补齐
        # end_smcode_no = ("0"*10 + smcode_end_no.lstrip("0x"))[-10:].upper()
        # 产品id转16进制
        # product_code = hex(int(product_id))
        # 补齐
        # product_code = ("0"*5 + product_code.lstrip("0x"))[-5:].upper()

        # start_no = "F%s%s"%(product_code, start_smcode_no)
        # end_no = "F%s%s"%(product_code, end_smcode_no)
        start_no = smcode_int + 1
        end_no = smcode_end_int
        # 生成数据记录
        smerpSmcode = SmerpSmcode(smerpsmcodeorder_id=order_id, smerpaccount_id= order.account_id, smerpproduct_id =product_id,num = num,
                                         start_no = start_no, end_no = end_no, publish_num = 0, publish_end_no = start_no, create_time = datetime.datetime.now() )
        smerpSmcode.save()

        # 更新该订单的状态
        order.pay_status = 2
        order.add_code_status = 2
        order.bank_order_id = bank_id
        order.save()

        logger.info(u"产品[%s]订单[%s]溯码生成成功"%(product_id, order_id))
    return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")



def smcode_int_to_hex(pre_product, smcode_int, pre_char):
    smcode_no = hex(int(smcode_int))
    #补齐
    smcode_hex_no = ("0"*10 + smcode_no.lstrip("0x"))[-10:].upper()
    return "%s%s%s"%(pre_char, pre_product, smcode_hex_no)



def save_excel_file(file_path, data_list, data_header, header_sort = None):
    header = data_header.keys()
    if header_sort:
        header = header_sort

    # wbk = xlwt.Workbook()
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet("Sheet1")
    # 写入表头
    for i, v in enumerate(header):
        sheet.write(0, i, data_header.get(v,""))

    # 写入数据
    for j, data in enumerate(data_list):
        _index = j + 1
        for i, v in enumerate(header):
            sheet.write(_index, i, data.get(v,""))

    workbook.save(file_path)



@user_authenticate
def SmErpSmcodeFileDown(request, *args, **kwargs):
    """
    溯码文件下载
    :param request:
    :return:
    """
    user = kwargs.get("user","")
    order_id = request.POST.get("orderid","")
    try:
        smcode = user.smerpaccountcodes.get(smerpsmcodeorder_id = order_id)
    except(KeyError, SmerpSmcode.DoesNotExist):
        logger.error(u"溯码订单[%s]不存在"%(order_id),exc_info=True)
        return HttpResponse(json.dumps(config.getErrInfo("SumaOrderError")), content_type="application/json")

    # 生成excel文件
    start_no = smcode.start_no
    end_no = smcode.end_no
    # print model_to_dict(smcode)
    product_id = smcode.smerpproduct.id
    # print product_id
    # 产品id转16进制
    product_code = hex(int(product_id))
    # 补齐
    product_code = ("0"*5 + product_code.lstrip("0x"))[-5:].upper()
    suma_code_list = []
    # suma_rc4 = RC4(config.RC4_KEY)
    for i in xrange(start_no, end_no + 1):
        # pass
        suma_code = {}
        smcode_src = smcode_int_to_hex(product_code, i, "F")
        suma_code["suma_index"] = i
        suma_code["suma_src"] = smcode_src
        suma_code["suma_encode"] = rc4.encode(smcode_src, config.RC4_KEY)
        suma_code_list.append(suma_code)

    # print suma_code_list
    # 写入excel表格

    # for order in orders:
    #     print model_to_dict(order)
    # print smcode
    file_name = "%s.xls"%(order_id)
    down_path = "smErp/static/smErp/down/order/"
    if not os.path.exists(down_path) or not os.path.isdir(down_path):
        os.makedirs(down_path)
    file_path = os.path.join(down_path, file_name)
    data_header = {"suma_index" : u"序号", "suma_src": u"原始号码", "suma_encode": u"加密号码"}
    header_sort = ["suma_index", "suma_src", "suma_encode"]
    try:
        save_excel_file(file_path, suma_code_list, data_header, header_sort)
    except:
        logger.error("",exc_info=True)
        return HttpResponse(json.dumps(config.getErrInfo("SystemError")), content_type="application/json")

    file_down_url = "/static/smErp/down/order/%s"%file_name
    ret = copy.deepcopy(config.getErrInfo("Success"))
    ret["file_down_url"] = file_down_url
    return HttpResponse(json.dumps(ret), content_type="application/json")


def SmErpUserProtocol(request):
    """
    用户协议
    :param request:
    :return:
    """
    try:
        config = SmplatConfig.smplatconfig_manage.get(name="user_protocol")
    except(KeyError, SmplatConfig.DoesNotExist):
        logger.error(u"用户协议的配置不存在",exc_info=True)

    return render(request, "smErp/common_template.html")


def SmErpForgetPassword(request):
    """
    忘记密码
    :param request:
    :return:
    """
    if request.method == "GET":
        return render(request, "smErp/forget_password.html")
    elif request.method == "POST":
        # print request.POST
        email = request.POST.get("email","")
        if not email:
            logger.error(u"重置密码：没有填入邮箱地址")
            ret = config.getErrInfo("EmailAddressError")
            return HttpResponse(json.dumps(ret), content_type="application/json")
        # 校验邮箱地址是否正确
        if not tl.is_email(email):
            logger.error(u"重置密码：填写的邮箱地址不正确[%s]"%email)
            ret = config.getErrInfo("EmailAddressError")
            return HttpResponse(json.dumps(ret), content_type="application/json")
        try:
            user = Account.account_manager.get(email = email)
        except(KeyError, Account.DoesNotExist):
            logger.error(u"重置密码：输入的账号[%s]不存在"%(email))
            return HttpResponse(json.dumps(config.getErrInfo("AccountNotExist")), content_type="application/json")

        try:
            # 发送忘记密码邮件
            now_datetime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            token = hashlib.md5("resetpasswd:%s:%s"%(email, now_datetime)).hexdigest()
            base64_email = base64.b64encode(email)
            redis_key = "reset_pwd:%s"% email
            cache.set(redis_key, token, 24 * 60 * 60)

            repassword_url = "http://%s/%s?token=%s&email=%s" % (config.HOST, "smErp/reset/password/", token, base64_email)
            html_message = '<div><p>你好!</p><p>忘记中国保健溯源平台密码了吗？别着急，请点击以下链接，我们协助您找回密码：' \
                           '<br><p style="word-wrap:break-word;word-break:break-all;"><a href="%s" target="_blank">%s</a>' \
                           '</p><p>如果这不是您的邮件请忽略，很抱歉打扰您，请原谅。</p></div>'%(repassword_url,repassword_url)
            subject = "找回中国保健溯源平台密码"
            send_ret = __send_mail(email, subject, html_message)
            if not send_ret:
                logger.error(u"重置密码:发送邮件失败[%s][%s]"%(email, send_ret))
                return HttpResponse(json.dumps(config.getErrInfo("EmailSendError")), content_type="application/json")

        except Exception, e:
            logger.error(u"重置密码：发送邮件异常[%s][%s]"%(email, e.message), exc_info=True)
            return HttpResponse(json.dumps(config.getErrInfo["SystemError"]), content_type="application/json")

        return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json")


def SmErpResetPassword(request):
    """
    重置密码
    :param request:
    :return:
    """
    if request.method == "GET":
        token = request.GET.get("token","")
        base64_email = request.GET.get("email","")
        # print request.GET
        if not (token and base64_email):
            # todo 没有信息，跳转到错误页面
            msg_error = u"提交的信息不全"
            return render(request, "smErp/error.html", {"msg_error": msg_error})
        # 判断缓存中是否还存在token
        try:
            email = base64.b64decode(base64_email)
        except:
            logger.error("重置密码：解密email[%s]异常"%(base64_email), exc_info=True)
            # email = ""
            # todo 跳转到错误提示页面
            msg_error = u"邮箱地址错误"
            return render(request, "smErp/error.html", {"msg_error": msg_error})

        redis_key = "reset_pwd:%s"% email
        _token  = cache.get(redis_key)
        if _token != token:
            logger.error(u"重置密码：token[%s] _token[%s]不相符"%(token, _token))
            # todo 跳转到错误提示页面
            msg_error = u"token信息错误"
            return render(request, "smErp/error.html", {"msg_error": msg_error})
        # 找到用户
        try:
            user = Account.account_manager.get(email=email)
        except(KeyError, Account.DoesNotExist):
            logger.error(u"重置密码：注册邮箱[%s]对应的用户不存在"%(email))
            # 跳转到错误页面
            msg_error = u"用户不存在"
            return render(request, "smErp/error.html", {"msg_error": msg_error})

        return render(request, "smErp/reset_password.html", {"token" : token, "old_pwd": user.passwd, "email": email})

    if request.method == "POST":
        # return HttpResponse(json.dumps(config.ERROR_CODE_INFO["Success"]), content_type="application/json" )
        # pass
        #
        # print request.POST
        email = request.POST.get("email","")
        token = request.POST.get("token","")
        new_pwd = request.POST.get("new_pwd","")
        old_pwd = request.POST.get("old_pwd","")
        if not (email and token and new_pwd and old_pwd):
            logger.error(u"重置密码：提交的参数错误")
            # todo 跳转到错误页面
            return HttpResponse(json.dumps(config.getErrInfo("ParamsError")), content_type="application/json" )
        # 判断token
        redis_key = "reset_pwd:%s"% email
        _token  = cache.get(redis_key)
        if _token != token:
            logger.error(u"重置密码：token[%s] _token[%s]不相符"%(token, _token))
            # todo 跳转到错误提示页面
            return HttpResponse(json.dumps(config.getErrInfo("TokenFailureError")), content_type="application/json" )
        # 判断新密码是否符合要求（密码必须包含数字、字母，区分大小写，最短8位，区分大小写）
        if not tl.is_password(new_pwd):
            logger.error(u"重置密码：新提交的密码[%s]不符合要求"%(new_pwd))
            return HttpResponse(json.dumps(config.getErrInfo("PasswordFormatError")), content_type="application/json" )
        try:
            user = Account.account_manager.get(email=email, passwd = old_pwd)
        except(KeyError, Account.DoesNotExist):
            logger.error(u"重置密码:账号[%s]密码[%s]不匹配"%(email, old_pwd))
            return HttpResponse(json.dumps(config.getErrInfo("AccountNotExist")), content_type="application/json" )

        md5_pwd = hashlib.md5("%s%s"%(new_pwd, config.PASSWORD_KEY)).hexdigest()
        # 重置密码
        user.passwd = md5_pwd
        user.save()
        # 清除token
        # 删除缓存
        cache.delete(redis_key)

        logger.info(u"用户[%s]重置密码[%s]-[%s]成功"%(email, new_pwd, md5_pwd))
        return HttpResponse(json.dumps(config.getErrInfo("Success")), content_type="application/json" )


def test1(request):
    # print request.POST
    ret = config.getErrInfo("Success")
    return HttpResponse(json.dumps(ret), content_type="application/json")